import logging

from django.contrib import admin, messages

import db
from .models import (
    Base,
    Buhreport,
    Container,
    Etaps,
    Images,
    It_lab,
    Mpp_podr,
    Patient,
    Pl_uslp,
    Sdl_set,
    Spr_access,
    Spr_lab,
    Spr_lpu,
    Spr_opl,
    Spr_sdl,
    User_sdl,
    Zav_report,
)

# Register your models here.
# admin.site.disable_action("delete_selected")


@admin.register(Mpp_podr)
class Mpp_podrAdmin(admin.ModelAdmin):
    list_display = ("mpp", "podr")
    list_display_links = ("mpp",)
    search_fields = ("mpp",)
    list_filter = ("mpp",)
    list_per_page = 25


@admin.register(Zav_report)
class ZavReportAdmin(admin.ModelAdmin):
    list_display = (
        "id",
        "mpp",
        "year",
        "month",
        "dn",
        "dk",
        "opl",
        "kol_lab",
        "kol_usl",
        "kol_all",
        "stu_lab",
        "stu_usl",
        "stu_all",
        "nars_lab",
        "nars_usl",
        "nars_lab_cancel",
        "nars_usl_cancel",
    )
    readonly_fields = ("dn",)
    list_display_links = ("id", "mpp")
    search_fields = ("mpp",)
    list_per_page = 10


@admin.register(Etaps)
class EtapsAdmin(admin.ModelAdmin):
    list_display = (
        "id",
        "naryad",
        "etap",
        "dz",
        "user",
        "sdl",
    )
    readonly_fields = ("dn",)
    list_display_links = ("id", "naryad")
    search_fields = ("naryad",)
    list_per_page = 25


class EtapsInline(admin.TabularInline):
    model = Etaps
    list_display = ("etap", "sdl__name_sdl", "user", "dn", "dz")
    readonly_fields = ("etap", "dn", "dz", "sdl", "user")
    extra = 0


class ImagesInline(admin.TabularInline):
    model = Images
    extra = 1
    # raw_id_fields = ("naryad",)
    readonly_fields = ("naryad",)
    list_select_related = ("naryad",)


class UslpInline(admin.TabularInline):
    model = Pl_uslp
    # list_display = ("idkv", "naryad", "kusl", "nusl", "kol", "price", "stu")
    # list_display = ("price", "stu")
    readonly_fields = (
        "idkv",
        "naryad",
        "usl",
        "kusl",
        "nusl",
        "kol",
        # "price",
        "stu",
        "uet",
        "tech",
        "pol",
        "lit",
        "cadcam",
        "gips",
    )
    list_select_related = ("naryad",)
    extra = 0


@admin.register(It_lab)
class It_labAdmin(admin.ModelAdmin):
    inlines = (ImagesInline, EtapsInline, UslpInline)
    # exclude = ("uslugi",)
    list_display_links = ("idkv",)
    list_display = (
        "admin_link",
        "idkv",
        "nkv",
        "patient",
        "dou",
        "dzr",
        "pdzr",
        "check_zav",
        "check_tech",
        "stu",
        "id_etap",
        "opl",
        "dn_etap",
        "dz_etap",
        "user_etap",
        "mpp_etap",
        "sdl_etap",
        "sdl_set",
        "user_etap_link",
        "image_count",
        "status",
    )
    list_select_related = (
        "patient",
        "sdl_etap",
        "sdl_set",
        "user_etap_link",
        "opl",
        "lpu",
    )
    list_filter = (
        "lpu",
        "opl",
        "id_etap",
        "sdl_etap",
        "profile_otd",
        "image_count",
    )

    search_fields = (
        "=nkv",
        "patient__fam",
    )
    raw_id_fields = (
        "sdl_set",
        "user_etap_link",
        "naryad_doc",
        "patient",
    )

    # readonly_fields = (
    #     "dou",
    #     "idkv",
    #     "nkv",
    # )
    list_per_page = 25

    actions = (
        "delete_selected",
        "de_close_nar",
        "de_pdzr_nar",
        "de_zav_nar",
        "move_to_lgr",
    )

    # def my_url_field(self, obj):
    #     return '<a href="%s">%s</a>' % (
    #         "http://localhost:3000/admin/changespec",
    #         obj.nkv,
    #     )

    # my_url_field.allow_tags = True
    # my_url_field.short_description = "Админ"

    @admin.action(description="Переместить на Ленинградский")
    def move_to_lgr(self, request, queryset) -> None:
        idkv = queryset.values_list("idkv", flat=True)[0]
        if idkv == 165:
            messages.error(request, "Наряд уже в Поликлинике 5")
        try:
            lpu = Spr_lpu.objects.filter(lpu=165).first()
            if lpu:
                db.write(f"update pl_uslk set lpu=165 where idkv='{idkv}'")
                It_lab.objects.filter(idkv=idkv).update(lpu=lpu)
            messages.success(
                request,
                "Успешно Перемещен в Поликлиника 3 (Ленинградский)",
            )
        except Exception as error:
            logging.exception("Found an error {error}")
            messages.error(request, str(error))

    @admin.action(description="Открыть наряд в Лаб-ии и Арене")
    def de_close_nar(self, request, queryset) -> None:
        idkv = queryset.values_list("idkv", flat=True)[0]
        try:
            db.write(f"update pl_uslk set dzr = NULL where idkv='{idkv}'")
            queryset.update(dzr=None)
            messages.success(request, "Успешно открыт наряд в Лаб-ии и Арене")
        except Exception as error:
            logging.exception("Found an error {error}")
            messages.error(request, str(error))

    @admin.action(description="Убрать ПДЗР, снять отметки")
    def de_pdzr_nar(self, request, queryset) -> None:
        idkv = queryset.values_list("idkv", flat=True)[0]
        try:
            queryset.update(pdzr=None, check_zav=False, check_tech=False)
            last_etap = queryset.order_by("-id_etap").first()
            last_etap.dz_etap = None
            last_etap.save()
            db.write(f"update pl_uslk set dzr=null, status=2 where idkv='{idkv}'")
        except Exception as error:
            logging.exception("Found an error {error}")
            messages.error(request, str(error))
        messages.success(
            request,
            "Успешно снята дата ПДЗР и отметки Зав. и Tex., B арене статус 2 дзр нул",
        )

    @admin.action(description="Убрать Зав")
    def de_zav_nar(self, request, queryset) -> None:
        try:
            queryset.update(check_zav=False)
            messages.success(request, "Отметка Зав установлена False")
        except Exception as error:
            logging.exception("Found an error {error}")
            messages.error(request, str(error))


@admin.register(Images)
class ImagesAdmin(admin.ModelAdmin):
    list_display = ("id", "naryad", "img")
    readonly_fields = ("thumbnail",)
    list_display_links = ("id", "naryad")
    search_fields = ("naryad__nkv",)
    list_per_page = 25


@admin.register(Spr_opl)
class Spr_oplAdmin(admin.ModelAdmin):
    list_display = ("id", "opl", "name_opl")
    list_display_links = ("id", "opl")
    search_fields = ("opl",)
    list_filter = ("opl",)
    list_per_page = 25


@admin.register(Spr_sdl)
class Spr_sdlAdmin(admin.ModelAdmin):
    list_display = ("id", "sdl", "name_sdl")
    list_display_links = ("id", "sdl")
    search_fields = ("sdl",)
    list_filter = ("sdl",)
    list_per_page = 25


@admin.register(Spr_lpu)
class Spr_lpuAdmin(admin.ModelAdmin):
    list_display = ("id", "lpu", "name_lpu")
    list_display_links = ("id", "lpu")
    search_fields = ("name_lpu",)
    list_filter = ("name_lpu",)
    list_per_page = 25


@admin.register(Pl_uslp)
class Pl_uslpAdmin(admin.ModelAdmin):
    list_display = (
        "idkv",
        "naryad",
        "kusl",
        "usl",
        "kol",
        "price",
        "stu",
    )
    readonly_fields = ("stu",)
    list_display_links = ("naryad", "usl")
    search_fields = ("naryad__nkv", "kusl")
    list_filter = ("naryad",)
    list_per_page = 25


@admin.register(Patient)
class PatientAdmin(admin.ModelAdmin):
    class Meta:
        model = Base
        readonly_fields = ("create_at", "update_at")

    list_display = ("id", "uid", "fam", "im", "ot", "dr", "adress")
    list_display_links = ("id", "fam")
    search_fields = ("fam",)
    list_filter = ("fam",)
    list_per_page = 25


@admin.register(Sdl_set)
class Sdl_setAdmin(admin.ModelAdmin):
    class Meta:
        model = Base
        readonly_fields = ("create_at", "update_at")

    list_display = ("id", "doc", "tech", "lit", "pol", "cadcam", "tech_st")
    list_display_links = ("id",)
    search_fields = ("id",)
    list_filter = ("id",)
    list_per_page = 25


admin.site.site_header = "Администрирование Helios"


@admin.register(Spr_access)
class Spr_accessAdmin(admin.ModelAdmin):
    list_display = ("id", "access", "access_name")
    list_display_links = ("id", "access", "access_name")
    search_fields = ("access", "access_name")
    list_filter = ("access", "access_name")
    list_per_page = 25


@admin.register(Buhreport)
class  BuhreportAdmin(admin.ModelAdmin):
    list_display = ("id", "year", "month", "profile", "podr")
    list_display_links = ("id", )
    search_fields = ("year", "month")
    list_filter = ("year", "month", "profile", "podr")
    list_per_page = 25


@admin.register(User_sdl)
class User_sdlAdmin(admin.ModelAdmin):
    list_display = ("id", "fio", "user", "doc", "dolzh", "lpu")
    filter_horizontal = (
        "sdls",
        "access",
    )
    list_display_links = ("id", "user")

    search_fields = ("user__fam", "user__login", "sdls__name_sdl", "lpu__name_lpu")
    list_filter = ("user",)
    list_per_page = 25

    actions = (
        "to_pol5",
        "to_pol_kedr",
        "to_pol4",
        "to_pol3",
        "to_pol2",
        "to_pol1",
        "to_pol_topki",
    )

    @admin.action(description="Перевод в Пoл5")
    def to_pol5(self, request, queryset) -> None:  # noqa: ARG002
        queryset.update(lpu=7)

    @admin.action(description="Перевод в Кедровку")
    def to_pol_kedr(self, request, queryset) -> None:  # noqa: ARG002
        queryset.update(lpu=6)

    @admin.action(description="Перевод в Пoл4")
    def to_pol4(self, request, queryset) -> None:  # noqa: ARG002
        queryset.update(lpu=5)

    @admin.action(description="Перевод в Пoл3")
    def to_pol3(self, request, queryset) -> None:  # noqa: ARG002
        queryset.update(lpu=4)

    @admin.action(description="Перевод в Пoл2")
    def to_pol2(self, request, queryset) -> None:  # noqa: ARG002
        queryset.update(lpu=3)

    @admin.action(description="Перевод в Пoл1")
    def to_pol1(self, request, queryset) -> None:  # noqa: ARG002
        queryset.update(lpu=2)

    @admin.action(description="Перевод в Топки")
    def to_pol_topki(self, request, queryset) -> None:  # noqa: ARG002
        queryset.update(lpu=1)


class LabInline(admin.TabularInline):
    model = Spr_lab
    extra = 3


@admin.register(Spr_lab)
class Spr_labAdmin(admin.ModelAdmin):
    list_display = ("id", "lab", "name_lab")
    list_display_links = ("id", "lab")
    search_fields = ("lab", "name_lab")
    list_filter = ("lab", "name_lab")
    list_per_page = 25


@admin.register(Container)
class ContainerAdmin(admin.ModelAdmin):
    list_display = ("id", "used", "nkv")
    list_display_links = ("id",)
    search_fields = ("=id", "used", "=nkv")
    list_filter = ("used",)
    list_per_page = 1000

    actions = ("check_containers",)

    @admin.action(
        description="Проверить все контейнеры на закрытие нарядов",
    )
    def check_containers(self, request, queryset) -> None:  # noqa: C901
        count_edit = 0
        edit_list: list[int] = []
        for cont in queryset:
            if cont.used is False:
                cont.nkv = 0
                if cont.nkv > 0:
                    cont.save()
                    edit_list.append(cont.id)
                    count_edit += 1
            if cont.used is True:
                if cont.nkv == 0:
                    cont.used = False
                    cont.save()
                if cont.nkv > 0:
                    nar: It_lab | None = It_lab.objects.filter(
                        nkv=cont.nkv,
                        id_etap=0,
                    ).first()
                    if nar is not None:
                        if nar.dzr is None and nar.pdzr is None:
                            continue
                        nar_new: It_lab | None = It_lab.objects.filter(
                            nkv=cont.nkv,
                            id_etap=0,
                            dzr__isnull=True,
                            pdzr__isnull=True,
                            naryad_doc=nar.naryad_doc,
                            patient=nar.patient,
                        ).first()
                        if nar_new is not None:
                            cont.nkv = nar_new.nkv
                            cont.save()
                            edit_list.append(cont.id)
                            count_edit += 1

        if not edit_list:
            messages.success(request, "Освобождено 0 контейнеров")
        messages.success(
            request,
            f"Освобождено контейнеров кол-во: {count_edit} {edit_list}",
        )
